<template lang="html">
    <div class="single" ref="tableContainer">
      <el-card style="width: 100%; height: 80%;" shadow="never">
<el-button>添加用户</el-button>
  
        <art-table
          ref="dataTable"
          :data="pagedData"
          selection
          :currentPage="currentPage"
          :pageSize="pageSize"
          :total="totalItems"
          @current-change="handlePageChange"
          @size-change="handlePageSizeChange"
          @sort-change="handleSortChange"
          @header-dragend="handleColumnResize"
          :height="tableHeight"
        >
          <el-table-column
            v-for="column in visibleColumns"
            :key="column.prop"
            :prop="column.prop"
            :label="column.name"
            :sortable="column.sortable"
            :width="column.width"
            :min-width="column.minWidth || 100"
            :resizable="true"
            :fixed="column.fixed"
            :sort-orders="['ascending', 'descending']"
            :sort-order="column.sortOrder"
          >
            <template v-if="column.prop === 'product_name'" #default="{ row }">
              <el-tooltip effect="light" :content="row.product_name" placement="top">
                <span class="text-ellipsis-2">{{ row.product_name }}</span>
              </el-tooltip>
            </template>
  
            <template v-else-if="isNumericColumn(column.prop)" #default="{ row }">
              {{ formatNumber(row[column.prop]) }}
            </template>
          </el-table-column>
        </art-table>
      </el-card>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, computed, onMounted, nextTick, onBeforeUnmount } from 'vue'
  import type { FormInstance, TableInstance, TableColumnCtx } from 'element-plus'
  
  // 表单相关
  const searchFormRef = ref<FormInstance>()
  const searchForm = reactive({
    product_name: '',
    sku: '',
    brand: '',
    store_name: '',
    business_model: ''
  })
  
  // 分页相关
  const currentPage = ref(1)
  const pageSize = ref(10)
  
  // 表格引用
  const dataTable = ref<TableInstance>()
  const tableContainer = ref<HTMLElement>()
  
  // 列配置
  interface TableColumn {
    name: string
    prop: string
    show: boolean
    sortable?: boolean
    width?: string | number
    minWidth?: string | number
    fixed?: string | boolean
    resizable?: boolean
    sortOrder?: 'ascending' | 'descending' | null
  }
  
  const tableColumns = reactive<TableColumn[]>([
    { name: '商品名称', prop: 'product_name', show: true, width: 300, minWidth: 200, fixed: 'left' },
    { name: 'SKU', prop: 'sku', show: true, width: 150, minWidth: 120 },
    { name: '品牌', prop: 'brand', show: true, width: 120, minWidth: 100 },
    { name: '店铺名称', prop: 'store_name', show: true, width: 180, minWidth: 150 },
    { name: '经营模式', prop: 'business_model', show: true, width: 120, minWidth: 100 },
    { name: '浏览量(PV)', prop: 'page_views', show: true, width: 120, sortable: true },
    { name: '访客数(UV)', prop: 'visitors', show: true, width: 120, sortable: true },
    { name: '人均浏览量', prop: 'avg_pageviews', show: true, width: 120 },
    { name: '平均停留时长(秒)', prop: 'avg_duration', show: true, width: 150, sortable: true },
    { name: '成交人数', prop: 'buyers', show: true, width: 120, sortable: true },
    { name: '成交转化率(%)', prop: 'conversion_rate', show: true, width: 140, sortable: true },
    { name: '成交单量', prop: 'orders', show: true, width: 120, sortable: true },
    { name: '成交商品件数', prop: 'quantity', show: true, width: 140, sortable: true },
    { name: '成交金额', prop: 'gmv', show: true, width: 120, sortable: true },
    { name: '成交客单价', prop: 'avg_order_value', show: true, width: 120, sortable: true },
    { name: '加购人数', prop: 'cart_add_users', show: true, width: 120, sortable: true },
    { name: '加购转化率(%)', prop: 'cart_conversion_rate', show: true, width: 140, sortable: true },
    { name: '加购商品件数', prop: 'cart_quantity', show: true, width: 140, sortable: true }
  ])
  
  // 动态表格高度
  const tableHeight = ref(500)
  const updateTableHeight = () => {
    if (tableContainer.value) {
      const containerRect = tableContainer.value.getBoundingClientRect()
      const windowHeight = window.innerHeight
      const topOffset = containerRect.top
      tableHeight.value = windowHeight - topOffset - 220
    }
  }
  
  const resizeObserver = new ResizeObserver(() => {
    updateTableHeight()
  })
  
  onMounted(() => {
    if (tableContainer.value) {
      resizeObserver.observe(tableContainer.value)
    }
    window.addEventListener('resize', updateTableHeight)
    nextTick(updateTableHeight)
    loadColumnWidths()
  })
  
  onBeforeUnmount(() => {
    window.removeEventListener('resize', updateTableHeight)
    resizeObserver.disconnect()
  })
  
  // 表格数据
  const tableData = reactive(
    Array.from({ length: 30 }, (_, index) => ({
      product_name: `商品${index + 1} 测试商品名称${String.fromCharCode(65 + (index % 26))}`,
      sku: `SKU${1000000 + index}`,
      brand: `品牌${String.fromCharCode(65 + (index % 26))}`,
      store_name: `店铺${(index % 5) + 1}`,
      business_model: index % 2 === 0 ? '自营' : 'POP',
      page_views: Math.floor(Math.random() * 10000),
      visitors: Math.floor(Math.random() * 5000),
      avg_pageviews: (Math.random() * 3).toFixed(2),
      avg_duration: (Math.random() * 20).toFixed(2),
      buyers: Math.floor(Math.random() * 1000),
      conversion_rate: (Math.random() * 10).toFixed(2),
      orders: Math.floor(Math.random() * 800),
      quantity: Math.floor(Math.random() * 1200),
      gmv: (Math.random() * 100000).toFixed(2),
      avg_order_value: (Math.random() * 500).toFixed(2),
      cart_add_users: Math.floor(Math.random() * 600),
      cart_conversion_rate: (Math.random() * 8).toFixed(2),
      cart_quantity: Math.floor(Math.random() * 900)
    })) as any[]
  )
  
  // 计算属性
  const visibleColumns = computed(() => tableColumns.filter(col => col.show))
  
  // 先筛选
  const filteredData = computed(() => {
    return tableData.filter(item => {
      return Object.entries(searchForm).every(([key, value]) => {
        if (!value) return true
        const itemVal = item[key as keyof typeof item]
        return itemVal?.toString().toLowerCase().includes(value.toString().trim().toLowerCase())
      })
    })
  })
  
  // 再排序
  const sortedData = computed(() => {
    const sorted = [...filteredData.value]
    const activeSort = tableColumns.find(col => col.sortOrder)
    if (activeSort && activeSort.sortOrder) {
      sorted.sort((a, b) => {
        const prop = activeSort.prop
        const aValue = a[prop]
        const bValue = b[prop]
        if (activeSort.sortOrder === 'ascending') {
          return (aValue ?? 0) > (bValue ?? 0) ? 1 : -1
        } else {
          return (aValue ?? 0) < (bValue ?? 0) ? 1 : -1
        }
      })
    }
    return sorted
  })
  
  // 再分页
  const pagedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return sortedData.value.slice(start, end)
  })
  
  // 总条数
  const totalItems = computed(() => filteredData.value.length)
  
  // 表单操作
  const resetSearchForm = () => {
    searchFormRef.value?.resetFields()
    currentPage.value = 1
  }
  
  // 分页操作
  const handlePageChange = (page: number) => {
    currentPage.value = page
  }
  
  const handlePageSizeChange = (size: number) => {
    pageSize.value = size
    currentPage.value = 1
  }
  
  // 排序操作
  const handleSortChange = ({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) => {
    tableColumns.forEach(col => {
      if (col.prop === prop) {
        col.sortOrder = order
      } else {
        col.sortOrder = null
      }
    })
    currentPage.value = 1
  }
  
  // 列宽调整
  const handleColumnResize = (column: TableColumnCtx<any>, newWidth: number) => {
    const targetCol = tableColumns.find(col => col.prop === column.property)
    if (targetCol) {
      targetCol.width = newWidth
      saveColumnWidths()
    }
  }
  
  // 列宽持久化
  const saveColumnWidths = () => {
    const widths = tableColumns.reduce((acc, col) => {
      acc[col.prop] = col.width
      return acc
    }, {} as Record<string, string | number | undefined>)
    localStorage.setItem('tableColumnWidths', JSON.stringify(widths))
  }
  
  const loadColumnWidths = () => {
    try {
      const savedWidths = localStorage.getItem('tableColumnWidths')
      if (savedWidths) {
        const widthMap = JSON.parse(savedWidths)
        tableColumns.forEach(col => {
          const savedWidth = widthMap[col.prop]
          if (savedWidth && !isNaN(parseInt(savedWidth as string))) {
            col.width = parseInt(savedWidth as string)
          }
        })
      }
    } catch (e) {
      console.error('加载列宽失败:', e)
    }
  }
  
  // 工具函数
  const isNumericColumn = (prop: string) => {
    const numericProps = [
      'page_views', 'visitors', 'avg_pageviews', 'avg_duration',
      'buyers', 'conversion_rate', 'orders', 'quantity',
      'gmv', 'avg_order_value', 'cart_add_users', 'cart_conversion_rate', 'cart_quantity'
    ]
    return numericProps.includes(prop)
  }
  
  const formatNumber = (value: any) => {
    if (typeof value === 'number') {
      return value.toLocaleString()
    }
    return value
  }
  </script>
  
  <style scoped>
  .text-ellipsis-2 {
    display: -webkit-box;
    overflow: hidden;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  </style>
  